package thread.demo05_1.ReentrantLock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 使用ReentrantLock实现线程同步
 * 
 * @author mengzhang6
 *
 */
public class ReentrantLockDemo {

	public static void main(String[] args) {

		Lock lock = new ReentrantLock();

		new Thread(() -> runMethod(lock, 0), "thread1").start();
		new Thread(() -> runMethod(lock, 5000), "thread2").start();
		new Thread(() -> runMethod(lock, 1000), "thread3").start();
		new Thread(() -> runMethod(lock, 5000), "thread4").start();
		new Thread(() -> runMethod(lock, 1000), "thread5").start();
	}

	private static void runMethod(Lock lock, long sleepTime) {
		/**
		 * 代码段加锁
		 */
		// 加锁
		lock.lock();
		try {
			Thread.sleep(sleepTime);
			System.out.println("ThreadName:" + Thread.currentThread().getName());
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			// 解锁
			lock.unlock();
		}
	}
}
